/**
 * 调用接口获取菜单权限
 * @returns Promise<any[]>
 */
const get = async (): Promise<any[]> => {
	const store = useApiStore();
	return await store.api.menu.get();
};

/**
 * 设置默认选择
 * @param routers 
 */
const setDafaultSelect = (routers: any[]) => {
	const routerStore = useRouterStore();
	routerStore.routers = routers;
	if (routers.length > 0) {
		routers[0].meta.active = true;
		routerStore.select = routers[0];
	}
};

const dynamicViewsModules: any = import.meta.glob('@/views/**/*.{vue,tsx}');

/**
 * 获取布局组件
 */
const getLayoutComponent = (item: any) => {
	return item.component == "" ? import("@/layout/index.vue") : import("@/layout/default/index.vue");
};

/**
 * 获取模块
 * @param item 
 * @returns 
 */

const getDynamicViewsModule = (item: any) => {
	if (item.component == "" || item.component == "layout") {
		return getLayoutComponent(item);
	} else {
		const view = dynamicViewsModules[`/src${item.component}`];
		if (view != null) {
			return view();
		} else {
			return import("@/views/error/404.vue");
		}
	}
};

/**
 * 构建路由组件
 * @param item 
 * @param router 
 * @param index 
 * @returns 
 */
const createRouter = (item: any, router: any) => {
	const route = {
		path: item.path,
		component: () => getDynamicViewsModule(item),
		meta: {
			icon: item.icon,
			title: item.title,
			breadcrumb: true,
			hidden: false,
			requiresAuth: true,
			expanded: false,
			active: false
		},
		children: item.children.length > 0 ? (_ => creater(item.children, router))() : []
	};
	return route;
};

/**
 * 创建路由
 * @param list
 * @param router 
 * @param index 
 * @returns 
 */
const creater = (list: any[], router: any): any[] => {
	let arry: any[] = [];
	list.forEach(x => {
		arry.push(createRouter(x, router));
	});
	return arry;
};

/**
 * 添加路由
 * @param routers
 * @param router 
 */
const addRoute = (routers: any[], router: any) => {
	routers.forEach(x => {
		router.addRoute(x);
	});
};

const addNotFound = (router: any) => {
	router.addRoute({ path: '/:pathMatch(.*)*', name: 'NotFound', component: () => import("@/views/error/404.vue") });
};

/**
 * default
 */
export default async () => {
	const router = useRouter();
	const routers = await creater((await get()), router);
	addRoute(routers, router);
	addNotFound(router);
	setDafaultSelect(routers);
};